package main

import (
	"io/ioutil"
	"os"

	pathpkg "path"

	"github.com/bitly/go-simplejson"
)

type config struct {
	check_conn   *simplejson.Json
	ping_ips     string
	listen_addr  string
	auth_addr    string
	prome_addr   string
	log_file     string
	watcher_conf string
	interval     int64
	tags         map[string]string
}

func ReadConfig(fn string) (js *simplejson.Json, err error) {
	f, err := os.Stat(fn)
	checkErr(err)
	if f.IsDir() {
		log.Error("not a file!")
		os.Exit(2)
	}
	b, err := ioutil.ReadFile(fn)
	checkErr(err)
	js, err = simplejson.NewJson(b)
	checkErr(err)
	return js, nil
}

func ReadDir(fn string, conf *config) {
	info, err := os.Stat(fn)
	checkErr(err)
	if !info.IsDir() {
		log.Error("not a directory!")
		os.Exit(2)
	}
	files, err := ioutil.ReadDir(fn)
	checkErr(err)
	for _, f := range files {
		if f.Name() == "mas.json" {
			p := pathpkg.Join(fn, f.Name())
			js, err := ReadConfig(p)
			checkErr(err)
			conf.check_conn = js.Get("check_conn")
			conf.ping_ips = js.Get("ping_ips").MustString()
			conf.listen_addr = js.Get("listen_addr").MustString()
			conf.auth_addr = js.Get("auth_addr").MustString()
			conf.interval = js.Get("interval").MustInt64()
			conf.log_file = js.Get("log_file").MustString()
			conf.prome_addr = js.Get("prome_addr").MustString()
			tags := js.Get("tags").MustMap()
			if conf.tags == nil {
				conf.tags = make(map[string]string)
			}
			for k, v := range tags {
				conf.tags[k] = v.(string)
			}
			conf.watcher_conf = fn
		}
	}
}

func CheckConfdir(cfdir string, conf *config) {
	if cfdir == "" {
		b := []byte(*check_conn)
		cc, _ := simplejson.NewJson(b)
		conf.check_conn = cc
		conf.ping_ips = *ping_ips
		conf.listen_addr = *listen_addr
		conf.auth_addr = *auth_addr
		conf.prome_addr = *prome_addr
		conf.log_file = *log_file
		conf.watcher_conf = *watcher_conf
		conf.interval = *interval
		conf.tags = *tags
	} else {
		//search confdir
		ReadDir(cfdir, conf)
	}
}
